package gerenciaDados.cln.cgt.PI.preProcessamento;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Segmentacao {
	public static BufferedImage thresholding(BufferedImage img){
		BufferedImage imgbw;
		double rw, rb; 			
		int nw, nb;			
		Color c;
		int largura = img.getWidth(), altura = img.getHeight();
		int [] pixels = img.getRGB(0, 0, largura, altura, null, 0, largura);
		int [] npixels = new int[largura*altura];
		double parr;
		double nparr=150;
																										
		do{
			rw=rb=0; 			
			nw=nb=0;						
			parr = nparr;					
			for (int col = 0; col < largura; col++) {
			  for (int lin = 0; lin < altura; lin++) {			    
			   c = new Color(pixels[largura * lin + col]);						    
			   if( c.getRed() > parr){
			    	npixels[largura * lin + col] = Color.WHITE.getRGB();
					rw += c.getRed();					
					nw++;
			    }else{
			    	npixels[largura * lin + col] = Color.BLACK.getRGB();
					rb += c.getRed();					
					nb++;
			    }			    			    			    			    			
			  }
			}
			nparr = ((rw/nw)+(rb/nb))/2;						
		}while(Math.abs(nparr-parr) > 0);
		
		imgbw = new BufferedImage(largura, altura, img.getType());
		imgbw.setRGB(0, 0, largura, altura, npixels, 0, largura);	
		
		return imgbw;
	}
	
	public static BufferedImage thresholdingRGB(BufferedImage img, String namefile){
		BufferedImage imgbw;
		double rw, gw, bw,rb, gb, bb; 			
		int nw, nb;			
		Color c;
		int largura = img.getWidth(), altura = img.getHeight();
		int [] pixels = img.getRGB(0, 0, largura, altura, null, 0, largura);
		int [] npixels = new int[largura*altura];
		double parr, parg, parb;
		double nparr=150, nparg=150, nparb=150;
																										
		do{
			rw=gw=bw=rb=gb=bb=0; 			
			nw=nb=0;						
			parr = nparr;
			parg = nparg;
			parb = nparb;			
			for (int col = 0; col < largura; col++) {
			  for (int lin = 0; lin < altura; lin++) {			    
			   c = new Color(pixels[largura * lin + col]);						    
			   if( c.getRed() > parr || c.getGreen() > parg || c.getBlue() > parb ){
			    	npixels[largura * lin + col] = Color.WHITE.getRGB();
					rw += c.getRed();
					gw += c.getGreen();
					bw += c.getBlue();
					nw++;
			    }else{
			    	npixels[largura * lin + col] = Color.BLACK.getRGB();
					rb += c.getRed();
					gb += c.getGreen();
					bb += c.getBlue();
					nb++;
			    }			    			    			    			    			
			  }
			}
			nparr = ((rw/nw)+(rb/nb))/2;
			nparg = ((gw/nw)+(gb/nb))/2;
			nparb = ((bw/nw)+(bb/nb))/2;				
		}while(Math.abs(nparr-parr) > 0 && Math.abs(nparg-parg) > 0 && Math.abs(nparb-parb) > 0);
		
		imgbw = new BufferedImage(largura, altura, img.getType());
		imgbw.setRGB(0, 0, largura, altura, npixels, 0, largura);	
		
		return imgbw;
	}
}
